using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Shared.Enums;

namespace UniversalAdmin.WebApi.Controllers;

[ApiController]
[Route("api/v1/[controller]")]
public class DocumentController : ControllerBase
{
    private readonly IDocumentService _documentService;
    private readonly IDocumentPermissionService _documentPermissionService;

    public DocumentController(
        IDocumentService documentService,
        IDocumentPermissionService documentPermissionService)
    {
        _documentService = documentService;
        _documentPermissionService = documentPermissionService;
    }

    [HttpGet]
    public async Task<IActionResult> GetDocuments(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 10,
        [FromQuery] DocumentStatus? status = null,
        [FromQuery] string? keyword = null)
    {
        var result = await _documentService.GetDocumentsAsync(page, pageSize, status, keyword);
        return Ok(result);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetDocumentById(Guid id)
    {
        // 检查权限
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (!string.IsNullOrEmpty(userId) && !await _documentPermissionService.CheckPermissionAsync(id, Guid.Parse(userId), PermissionType.Read))
        {
            return Forbid();
        }

        var document = await _documentService.GetDocumentByIdAsync(id);
        if (document == null)
        {
            return NotFound();
        }
        return Ok(document);
    }

    [HttpPost]
    [Authorize]
    public async Task<IActionResult> CreateDocument([FromBody] CreateDocumentDto dto)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        try
        {
            var document = await _documentService.CreateDocumentAsync(dto, Guid.Parse(userId));
            return CreatedAtAction(nameof(GetDocumentById), new { id = document.Id }, document);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpPut("{id}")]
    [Authorize]
    public async Task<IActionResult> UpdateDocument(Guid id, [FromBody] UpdateDocumentDto dto)
    {
        // 检查权限
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        // 检查是否为文档所有者
        var document = await _documentService.GetDocumentByIdAsync(id);
        if (document == null)
        {
            return NotFound();
        }

        if (document.CreatedBy != Guid.Parse(userId))
        {
            // 非所有者需要管理员权限
            if (!User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
            {
                return Forbid();
            }
        }

        try
        {
            var updatedDocument = await _documentService.UpdateDocumentAsync(id, dto);
            if (updatedDocument == null)
            {
                return NotFound();
            }
            return Ok(updatedDocument);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpDelete("{id}")]
    [Authorize]
    public async Task<IActionResult> DeleteDocument(Guid id)
    {
        // 检查权限
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        // 检查是否为文档所有者
        var document = await _documentService.GetDocumentByIdAsync(id);
        if (document == null)
        {
            return NotFound();
        }

        if (document.CreatedBy != Guid.Parse(userId))
        {
            // 非所有者需要管理员权限
            if (!User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
            {
                return Forbid();
            }
        }

        var result = await _documentService.DeleteDocumentAsync(id);
        if (!result)
        {
            return NotFound();
        }
        return NoContent();
    }

    [HttpPatch("{id}/status")]
    [Authorize]
    public async Task<IActionResult> UpdateDocumentStatus(Guid id, [FromBody] DocumentStatus status)
    {
        // 检查权限
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        // 只有管理员和超级管理员可以修改文档状态
        if (!User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        var result = await _documentService.UpdateDocumentStatusAsync(id, status);
        if (!result)
        {
            return NotFound();
        }
        return Ok();
    }

    [HttpGet("user")]
    [Authorize]
    public async Task<IActionResult> GetDocumentsByUser(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 10)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var documents = await _documentService.GetDocumentsByUserAsync(Guid.Parse(userId), page, pageSize);
        return Ok(documents);
    }

    [HttpPost("upload")]
    [Authorize]
    public async Task<IActionResult> UploadDocument([FromBody] UploadDocumentDto dto)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        try
        {
            var document = await _documentService.UploadDocumentAsync(dto, Guid.Parse(userId));
            return CreatedAtAction(nameof(GetDocumentById), new { id = document.Id }, document);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpGet("{id}/related")]
    public async Task<IActionResult> GetRelatedDocuments(Guid id, [FromQuery] int limit = 5)
    {
        // 检查权限
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (!string.IsNullOrEmpty(userId) && !await _documentPermissionService.CheckPermissionAsync(id, Guid.Parse(userId), PermissionType.Read))
        {
            return Forbid();
        }

        var documents = await _documentService.GetRelatedDocumentsAsync(id, limit);
        return Ok(documents);
    }
}